﻿<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="puzzles" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ import Namespace="RobozzleModel" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Collections.Generic" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>RoboZZle Javascript - Alpha</title>
    <link href="../stats.css" rel="stylesheet" type="text/css"/>
    <style type="text/css">
    #loginBar { position: absolute; top: 20px; right: 80px; }
    </style>    
</head>
<body>

<h1>RoboZZle Javascript - Alpha</h1>

<div id='loginBar'>
<%= JsUtils.LoginBar(Server.UrlEncode(Request.Url.PathAndQuery)) %>
</div>

<div style="text-align:center; margin-bottom: 30px;">
<p>
<%
    const string STR_DATE = "date", STR_AUTHOR = "author", STR_DIFF = "difficulty", STR_LIKED = "liked";
    string sortByParam = Request.Params["sortby"];
    if (!new[] { STR_AUTHOR, STR_DIFF, STR_LIKED }.Contains(sortByParam)) sortByParam = STR_DATE;

    Func<string, string, string> format =
        (paramName, label)
            => string.Format(
                "{0}{1}{2}",
                paramName == sortByParam ? "<b>" : "<a href=\"index.aspx?sortby=" + paramName + "\">",
                label,
                paramName == sortByParam ? "</b>" : "</a>");    
             
    Response.Write(
        string.Format(
            "{0} | {1} | {2} | {3}",
            format(STR_DATE, "By date"),
            format(STR_AUTHOR, "By author"),
            format(STR_DIFF, "By difficulty"),
            format(STR_LIKED, "By how liked")));
%>
</p>
</div>
<table>
<thead>
<tr> <th>Id</th> <th>Title</th> <th>Solved?</th> <th>Author</th> <th>Difficulty</th> <th>Liked / Disliked</th> <th></th></tr>
</thead>

<%   
         RobozzleModel.RobozzleEntities entities = new RobozzleModel.RobozzleEntities();

         var commentCounts = 
             entities.ForumComment
                .GroupBy(comment => comment.ForumThread)
                .Select(g => new { PuzzleId = g.Key.PuzzleId, Count = g.Count() })
                .Where(p => p.PuzzleId != null)
                .ToDictionary(p => p.PuzzleId);

         int row = 0;
         var levels = Queries.VisiblePuzzles(entities).AsEnumerable();

         Func<double, double, double> avgDifficulty = 
             (double sum, double count) => (count == 0 ? double.MaxValue : sum / count);
         Func<double, double, double> avgCoolness =
             (double sum, double count) => (count == 0 ? 0.5 : (sum + count) / 2 / count);
         
         levels = 
             (sortByParam == STR_AUTHOR) ? levels.OrderBy(level => level.SubmittedBy)
             : (sortByParam == STR_DIFF) ? levels.OrderBy(level => avgDifficulty(level.DifficultyVoteSum, level.DifficultyVoteCount) )
             : (sortByParam == STR_LIKED) ? levels.OrderByDescending(level => avgCoolness(level.CoolnessVoteSum, level.CoolnessVoteCount) )
             : levels.OrderBy(level => level.SubmittedDate).Reverse();

         Dictionary<int, bool> solvedLevels;

         string userName = HttpContext.Current.User.Identity.Name;

         if (!HttpContext.Current.User.Identity.IsAuthenticated)
         {
             solvedLevels = new Dictionary<int, bool>();
         }
         else
         {
             solvedLevels =
                 entities.Solution.Where(l => l.UserName == userName && l.LevelId >= 0)
                 .GroupBy(l => l.LevelId)
                 .Select(g => g.Key)
                 .ToDictionary(r => r, r => true);
         }
         
         foreach (var level in levels)
         {
             string rowClass = StatsCommon.RowClass(row++);
             string difficulty, likedness;
             StatsCommon.ConvertVotes(level, out likedness, out difficulty);
             int commentCount = commentCounts.ContainsKey(level.Id) ? commentCounts[level.Id].Count : 0;
        %>
            <tr>
                <td class="<%=rowClass%>" style="text-align: left"><%= level.Id %></td>
                <td class="<%=rowClass%>" style="text-align: left"><a href="play.aspx?puzzle=<%= level.Id %>"><%= Server.HtmlEncode(level.Title) %></a></td>
                <td class="<%=rowClass%>"><%= solvedLevels.ContainsKey(level.Id) ? "X" : "&nbsp;" %></td>                
                <td class="<%=rowClass%>" style="text-align: left"><a href="user.aspx?name=<%= level.SubmittedBy %>"><%= level.SubmittedBy %></a></td>
                <td class="<%=rowClass%>"><%= difficulty %></td>
                <td class="<%=rowClass%>"><%= likedness %></td>
                <td class="<%=rowClass%>"><a href="forums/thread.aspx?puzzle=<%= level.Id %>"><%= StatsCommon.Plural("comment", commentCount) %></a></td>
            </tr>
        <%     
         }
     %>
</table>
<%
     Response.Write(StatsCommon.Footer());
%>
</body>
</html>
